<?php
/**
 * Enter description here ...
 * @author Micou13630
 *
 */
class HttpResponse {

	private $request;

	/**
	 * Enter description here ...
	 * @param HTTPRequest $request
	 */
	public function HttpResponse(HttpRequest $request = null) {
		$this->request = $request;
	}

	/**
	 * Enter description here ...
	 * @return string|boolean
	 */
	public function getContent() {
		if ($this->request->isDataSourceRequest()) {
			$this->getDataSource();
		} else {
			$this->getScreen();
		}
	}
	
	/**
	 * Enter description here ...
	 */
	public function getScreen() {
		if ($this->request->isAuthenticationRequest()) {
			$_SESSION["#AUTH#"]->login($this->request->_username, $this->request->_password);
		}
		
		$auth = $_SESSION["#AUTH#"];
		if (isset($auth) && !$auth->isLogged()) {			
			$scr = new LoginScreen();
			$scr->render();
			return;	
		}		

		
		$screen = Config::getParams()->PATH_USER_INTERFACE.$this->request->getScreen().'.php';

		if (is_file($screen)) {
			ob_start();
			include $screen;
			$contents = ob_get_contents();
			ob_end_clean();
			echo $contents;
		} else {
			MessageCollectionLog::getInstance()->addMessage(new MessageLog(MessageLog::TYPE_WARN, $this->request->getScreen(), 'Screen inconnu'));
			$this->getError();
		}
	}
	
	/**
	 * Enter description here ...
	 */
	public function getDataSource() {
		
		$auth = $_SESSION["#AUTH#"];
		if (isset($auth) && !$auth->isLogged()) {
			$connector = new JSONConnector(new ErrorDataAccessDao(IDataSetDao::STATUS_LOGIN_REQUIRED,''), $this->request);
			echo $connector->response();
			return;
		}
		
		$ds = Config::getParams()->PATH_DATA_SOURCE.$this->request->getDataSource().'.php';

		if (is_file($ds)) {
			ob_start();
			include $ds;
			$contents = ob_get_contents();
			ob_end_clean();
			echo $contents;
			// Classe DataSource			
			$class = $this->request->getDataSource();
			$instance = new $class;
			if ($instance instanceof IDataAccessDao) {
				$connector = new JSONConnector($instance, $this->request);
				echo $connector->response();
			}
		} else {
			MessageCollectionLog::getInstance()->addMessage(new MessageLog(MessageLog::TYPE_ERROR, $this->request->getDataSource(), 'DataSource inconnue'));
			$this->getError();
		}
	}

	/**
	 * Enter description here ...
	 * @return string|boolean
	 */
	public function getError() {
		$screen = new Screen("Error");
		$screen->render();
	}
}
?>
